package jmine.tec.rpc.server.representation.representers.lazy;

import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.List;

import jmine.tec.rpc.server.representation.RepresentationContext;
import jmine.tec.rpc.server.representation.representers.reflection.ListPropertyRepresenter;
import jmine.tec.rpc.server.representation.representers.reflection.RepresenterUtil;
import bancosys.tec.persist.Persistable;

/**
 * Representador lazy de listas
 * 
 * @author lundberg
 * @param <R> tipo de representação
 * @param <E> tipo de entidade representada
 */
public class LazyListPropertyRepresenter<R, E> extends ListPropertyRepresenter<R, E> {

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isApplicableTo(PropertyDescriptor representationProperty) {
        return super.isApplicableTo(representationProperty) && RepresenterUtil.isLazy(representationProperty);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected List<?> createRepresentation(RepresentationContext context, Class<?> valueType, List<?> value) {
        List<Object> lazies = new ArrayList<Object>();
        context.register(value, lazies);
        for (Object object : value) {
            if (this.isLazyable(object)) {
                lazies.add(new LazyPersistableBean((Persistable) object));
            } else {
                lazies.add(object);
            }
        }
        return context.representObjects(valueType, lazies);
    }

    /**
     * Verifica se o objeto pode ser representado de forma lazy
     * 
     * @param object object
     * @return boolean
     */
    private boolean isLazyable(Object object) {
        return object instanceof Persistable;
    }
}
